﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using System.Net.Http;
namespace DemoPersonalizeSearch
{
    public partial class Search : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtQuery.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearch.ClientID + "')");
          
        
            //get option
            bool iscache = ckCache.Checked;
            bool isPersonal = ckIsPersonal.Checked;
            int maxResultGet, maxResultShowed;
            int.TryParse(txtMaxResult.Text, out maxResultGet);
            int.TryParse(txtMaxResultShowed.Text, out maxResultShowed);
            Option opt = new Option(iscache, isPersonal, maxResultGet, maxResultShowed);
            ViewState["SearchOptions"] = opt;


            lblError.Text = "";
            if (Session.IsLogin())
            {
                txtUsername.Visible = false;
                lblUsername.Visible = true;
                lblUsername.Text = "Wellcome, " + Session.UserLogin();
                btnSignIn.Text = "Log Out";

            }
            else
            {
                txtUsername.Visible = true;
                lblUsername.Visible = false;
                btnSignIn.Text = "Sign In";
            }

            // ẩn hiện option panel
            Option opt1 = Session.getOptions();
            ckCache.Checked = opt1.IsCache;
            ckIsPersonal.Checked = opt1.IsPersonal;
            txtMaxResult.Text = opt1.MaxResultGet.ToString();
            txtMaxResultShowed.Text = opt1.MaxResultShowed.ToString();

            List<string> expansion = new List<string>();
            QueryExpansion qe = new QueryExpansion();
            if (txtQuery.Text != "")
            {
                expansion = qe.ExpansionQuery(txtQuery.Text, 1, Session.UserLoginData());

                if (expansion.Count == 0)
                {
                    expansion = qe.ExpansionQuery(txtQuery.Text, 2, Session.UserLoginData());

                }
                
                blExpansion.DataSource = expansion;
                Session["expansion"] = expansion;
                blExpansion.DataBind();
            }

        }

        protected void btnSignIn_Click(object sender, EventArgs e)
        {
            if (!Session.IsLogin())
            {
                
                DeliciousDatabaseDataContext db = new DeliciousDatabaseDataContext();
                UserData ud = db.UserDatas.Where(x => x.Username == txtUsername.Text.Trim()).FirstOrDefault();
                if (ud != null)
                {
                    txtUsername.Visible = false;
                    lblUsername.Visible = true;
                    lblUsername.Text = "Wellcome, " + ud.Username;
                    if (txtUsername.Text != "")
                    {
                        Session.AddUserLogin(txtUsername.Text);
                    }
                    btnSignIn.Text = "Log Out";
                }
                else
                {
                    lblError.Text = "User not found!";
                }

            }
            else
            {
                txtUsername.Visible = true;
                lblUsername.Visible = false;
                Session.RemoveLogin();
                btnSignIn.Text = "Sign In";
            }

        }

        protected void BtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            long start = DateTime.Now.Ticks;
            string query = txtQuery.Text.Trim();
            PersonalizeSearch ps = new PersonalizeSearch();
            Object data;
            DeliciousDatabaseDataContext db = new DeliciousDatabaseDataContext();
            int limit = 25;
            limit = Session.getOptions().MaxResultGet;
            if (Session.IsLogin() && Session.getOptions().IsPersonal)
             data = ps.Search(query, limit,Session.getOptions().IsCache,db.UserDatas.Where(x=>x.Username == Session.UserLogin()).FirstOrDefault());
            else data = ps.Search(query, limit, Session.getOptions().IsCache, null);
            
            DlResultSearch.DataSource = data;
            DlResultSearch.DataBind();
            int count = DlResultSearch.Items.Count;
            if (count > 0)
                ResultCount.Text = "Found " + count + " result.";
            else ResultCount.Text = "No Result Found!";
            long end = DateTime.Now.Ticks;
            TimeSearch.Text = String.Format("Searched in {0}s", (end - start) / 10000000);
            //
            
            
            
        }

        protected void BtnOptions_Click(object sender, EventArgs e)
        {
            
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            Option opt = (Option)ViewState["SearchOptions"];
            Session.setOptions(opt);
            ckCache.Checked = opt.IsCache;
            ckIsPersonal.Checked = opt.IsPersonal;
            txtMaxResult.Text = opt.MaxResultGet.ToString();
            txtMaxResultShowed.Text = opt.MaxResultShowed.ToString();
           
            Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey","inform();",true);
        }

        protected void ckCache_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void blExpansion_Click(object sender, BulletedListEventArgs e)
        {
            if (Session["expansion"]!=null)
            {
                List<string> list = (List<string>)Session["expansion"];
                txtQuery.Text = txtQuery.Text.Trim() + " " + list[e.Index];
                list.RemoveAt(e.Index);
            }
            List<string> expansion = new List<string>();
            QueryExpansion qe = new QueryExpansion();
            if (txtQuery.Text != "")
            {
                expansion = qe.ExpansionQuery(txtQuery.Text, 1,null);

                if (expansion.Count == 0)
                {
                    expansion = qe.ExpansionQuery(txtQuery.Text, 2,null);

                }

                blExpansion.DataSource = expansion;
                Session["expansion"] = expansion;
                blExpansion.DataBind();
            }
        }

        
    }
}